package com.leinao.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.leinao.commons.Response;
import com.leinao.config.EnvironmentConfig;
import com.leinao.constant.Constant;
import com.leinao.constant.ProjectEnum;
import com.leinao.constant.ProjectErrorEnum;
import com.leinao.constant.ProjectJobHandleEnum;
import com.leinao.job.dao.PaiProjectJobMapper;
import com.leinao.job.dto.JobInfoDto;
import com.leinao.job.dto.PaiJobEnvironment;
import com.leinao.job.dto.ProjectJobViewDto;
import com.leinao.project.dao.PublicProjectMapper;
import com.leinao.project.service.PublicProjectService;
import com.leinao.util.page.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: weiwei
 * @Date: 2019/6/6 15:19
 * @Description:
 * @Version 1.0
 */
@Service
public class PublicProjectServiceImpl implements PublicProjectService {

    private static Logger logger = LoggerFactory.getLogger(PublicProjectServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PublicProjectMapper publicProjectMapper;

    @Autowired
    private EnvironmentConfig env;

    @Autowired
    private PaiProjectJobMapper paiProjectJobMapper;

    
    /**
      * @Description   获取任务信息
      * @param publicJobId 任务Id
      * @param token
      * @return
      * @author:    weiwei
      * @Date:  2019/6/10 13:33
      */
    @Override
    public Response<ProjectJobViewDto> getUserPublicTaskDetail(Long publicJobId, String token) {

        ProjectJobViewDto userPublicTaskDetail = new ProjectJobViewDto();
        try {

            //根据Id获取任务状态
            userPublicTaskDetail = publicProjectMapper.getUserPublicTaskDetail(publicJobId);
            logger.debug("getUserPublicTaskDetail info: {}", userPublicTaskDetail);

            if(null == userPublicTaskDetail){
                return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.PUBLIC_JOB_IS_NOT_EXIST.getSeq(),
                                     ProjectJobHandleEnum.PUBLIC_JOB_IS_NOT_EXIST.getDesc(), null);
            }
            long timeConsuming = userPublicTaskDetail.getCompletedTime() - userPublicTaskDetail.getCreateTime();
            userPublicTaskDetail.setTimeConsuming(timeConsuming);

            return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.GET_SUCCESS.getSeq(),
                                    ProjectJobHandleEnum.GET_SUCCESS.getDesc(), userPublicTaskDetail);
        } catch (Exception e) {
            logger.error("loadJobDetail error", e);
            return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.LOAD_JOB_INFO_ERROR.getSeq(),
                                    ProjectJobHandleEnum.LOAD_JOB_INFO_ERROR.getDesc(), userPublicTaskDetail);
        }
    }

    @Override
    public Response<PageInfo> getProjectPublicJob(Long projectId, Integer pageNumber, Integer pageSize) {

        PageInfo pageInfo = null;
        PageHelper.startPage(pageNumber, pageSize);
        List<JobInfoDto> projectList = Lists.newArrayList();

        try {
            Integer projectType = publicProjectMapper.getProjectType(projectId);

            if(null == projectType){
                return Response.ok(Constant.RESPONSE_STATUS_SUCCESS,
                        ProjectEnum.PUBLIC_ID_IS_ERROR.getSeq(),ProjectEnum.PUBLIC_ID_IS_ERROR.getDesc(),null);
            }

            if(projectType.equals(0)){
                return Response.ok(Constant.RESPONSE_STATUS_SUCCESS,
                        ProjectEnum.PROJECT_IS_NOT_PUBLIC.getSeq(),ProjectEnum.PROJECT_IS_NOT_PUBLIC.getDesc(),null);
            }

            projectList = publicProjectMapper.getProjectPublicJob(projectId);
            pageInfo = new PageInfo(projectList);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ProjectEnum.GET_PROJECT_ERROR.getSeq(),ProjectEnum.GET_PROJECT_ERROR.getDesc(),null);
        }
        return Response.ok(pageInfo);
    }

    @Override
    public Response<Object> getJobInfo(Long publicJobId,  String token) {

        // 查询任务信息
        ProjectJobViewDto jobInfoDto = publicProjectMapper.getUserPublicTaskDetail(publicJobId);

        //查看某个任务
        return loadJobDetail(jobInfoDto, token);
    }


    /**
     * @Description 获取任务语言框架
     * @param publicJobId
     * @param token
     * @return
     * @author:    weiwei
     * @Date:  2019/6/6 13:55
     */
    @Override
    public Response<PaiJobEnvironment> getJobEnvironment(Long publicJobId, String token) {

        try {
            return Response.ok(paiProjectJobMapper.getPublicJobEnvironment(publicJobId));
        }catch (Exception e){
            logger.error("getJobEnvironment error");
            logger.error(e.getMessage(), e);
            return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.GET_JOB_ENVIRONMENT_ERROR.getSeq(),
                    ProjectJobHandleEnum.GET_JOB_ENVIRONMENT_ERROR.getDesc(), null);
        }
    }


    /**
     * @Description 	获取任务参数
     * @param publicJobId
     * @param token
     * @return
     * @author:    weiwei
     * @Date:  2019/6/6 14:00
     */
    @Override
    public Response<String> getJobParams(Long publicJobId, String token) {

        try {
            return Response.ok(publicProjectMapper.getPublicJobConfig(publicJobId));
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ProjectErrorEnum.GET_PUBLIC_JOB_PARAMS_ERROR.getSeq(),
                    ProjectErrorEnum.GET_PUBLIC_JOB_PARAMS_ERROR.getDesc(),null);
        }
    }

    /**
     * @description 查看任务详情
     * @param token
     * @return
     * @author  cuidongdong
     * @date 2019.5.9 11:40:00
     */
    private Response<Object> loadJobDetail(ProjectJobViewDto jobInfoDto, String token) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Authorization", "Bearer " + token);
        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        String body = "";
        try {
            String config = jobInfoDto.getConfig();
            Map<Object,Object> map = new HashMap<Object,Object>();
            if(StringUtils.isNotBlank(config)) {
                map.put("jobConfig", config);
            }
            ResponseEntity<String> responseEntity = restTemplate.exchange(env.getRestServerUrl() + Constant.REST_SERVER_LOAD_JOB_API + jobInfoDto.getJobName(),
                    HttpMethod.GET, formEntity, String.class);
            logger.debug(String.format("request getJobDetail return: {}", JSON.toJSON(responseEntity)));
            if (responseEntity.getStatusCodeValue() == Constant.RESPONSE_STATUS_SUCCESS) {
                logger.debug("loadJobDetail success");
                body = responseEntity.getBody();
                JSONObject jsonObj = JSON.parseObject(body);
                logger.info(String.format("loadJobDetail resp: {}", jsonObj));
                map.put("jobDetail", jsonObj);
                return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.GET_SUCCESS.getSeq(), ProjectJobHandleEnum.GET_SUCCESS.getDesc(), map);
            }
            return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.GET_ERROR.getSeq(), ProjectJobHandleEnum.GET_ERROR.getDesc(), null);
        } catch (Exception e) {
            logger.error("loadJobDetail error");
            logger.error(e.getMessage(), e);
            return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.GET_ERROR.getSeq(), ProjectJobHandleEnum.GET_ERROR.getDesc(), null);
        }
    }

}
